#!/usr/bin/python
# -*- coding: utf-8 -*-
#Under the terms of the General Public License v.3
#For more information see LICENSE.txt

from Player import *
import time
import thread

class Human (Player):

	def __init__(self, image, posX, posY, level, apList):
		Player.__init__(self, image, posX, posY)
		self.initConstants(level)
		self.isAlive(True)
		self.setLevel(level)
		self.apList = apList
		thread.start_new_thread(self.start, (0, 0))

	def initConstants(self, level):
		self.PAINT_DELAY_MS = 50
		self.TIME_TO_KILL_AP = level
		self.TIME_POWER_RATIO_AP = 0.01
		self.TIME_TO_SLEEP = 30
		self.NEAR_DISTANCE = 15

	def start(self, nothing0, nothing1):
		for ap in self.apList:
			self.setAp(ap)
			self.killAp()

	def paint(self, screen):
		thread.start_new_thread(self.paintThread, (screen, 0))
	
	def paintThread(self, screen, nothing):
		while self.isAlive():
			pygame.time.delay(self.PAINT_DELAY_MS)
			screen.blit(self.image, (self.getPosX(), self.getPosY()))
			pygame.display.flip()
	
	def getLevel(self):
		return self.level

	def setLevel(self, level):
		self.level = level

	def isAlive(self):
		return self.alive

	def isAlive(self, alive):
		self.alive = alive

	def killHuman(self):
		self.isAlive(False)

	def killAp(self):
		xSign = int((self.getAp().getPosX() - self.getPosX()) / abs(self.getAp().getPosX() - self.getPosX()))
		ySign = int((self.getAp().getPosY() - self.getPosY()) / abs(self.getAp().getPosY() - self.getPosY()))
		xDist = abs(self.getAp().getPosX() - self.getPosX())
		yDist = abs(self.getAp().getPosY() - self.getPosY())
		self.setSpeedX(self.getLevel() * xSign)
		self.setSpeedY(yDelta = int(abs(xDelta) * ySign * yDist / xDist))

		while (not self.isNearAp()):
			self.updatePosition()
			time.sleep(self.TIME_TO_SLEEP)

		time.sleep(sleep.TIME_TO_KILL_AP + self.TIME_POWER_RATIO_AP * self.getAp().getPower())
		self.getAp().turnOff()

	def isNearAp(self):
		xDist = abs(self.getAp().getPosX() - self.getPosX())
		yDist = abs(self.getAp().getPosY() - self.getPosY())

		if ((xDist <= self.NEAR_DISTANCE) and (yDist <= self.NEAR_DISTANCE)):
			return True
		else:
			return False
	
	def getAp(self):
		return self.ap

	def setAp(self, ap):
		self.ap = ap
